#ifndef SSHCONSOLE_H
#define SSHCONSOLE_H

#include <QTextEdit>
#include "sshconnection.h"
#include "ansiescapecodehandler.h"

/*
    继承了 QTextEdit GUI类
    整体功能:
        实现了ssh控制台的相关功能
    具体功能：
        1、使用封装好的libssh相关功能链接ssh会话，并多线程接受和传递数据、命令
        2、使用ANSI解析器解析接受到的数据，并将其中的ANSI颜色转义序列转为响应的颜色
        3、显示相关功能
*/

class SshConsole final : public QTextEdit
{
public:
    explicit SshConsole(const Ssh::SshLoginKeys& loginKeys, QWidget* parent = nullptr);
    ~SshConsole() override;

    void SetPrompt(const QString& prompt, bool IsShowPrompt = true);
    void SetIsShowPrompt(bool isShowPrompt);
    [[nodiscard]] bool IsShowPrompt() const;
    void ExecCommand(const QString& command);

    // SetTheme

protected:
    void mousePressEvent(QMouseEvent *event) override;
    void mouseMoveEvent(QMouseEvent *event) override;
    void mouseReleaseEvent(QMouseEvent *event) override;
    void keyPressEvent(QKeyEvent* event) override;
    void ShowHistoryCommand(int key);

private slots:
    void DoWhenConnected();
    void GetExecStandardOutput(const std::string& output);
    void GetExecStandardError(const std::string& error);
    void DoWhenExecFinished();

private:
    void Init(const Ssh::SshLoginKeys& loginKeys);
    void InitUi();
    bool IsMouseInEditableZone();
    bool IsMouseInEditableZone(const QPoint& pos);
    void ReplaceCurrentCommand(const QString& command);
    bool MoveCursorByKey(int key);
    bool RemoveForwardByKey(int key);
    // 过滤无用的前两行和最后一行{:~/}
    QString FilterUnusedChars(QString string);

    // 会话线程
    QThread* mSshThread {nullptr};
    Ssh::SshConnection* mSshConnection {nullptr};

    // ANSI序列解析器
    Utils::AnsiEscapeCodeHandler mAnsiCodeHandler = Utils::AnsiEscapeCodeHandler();
    bool isRemoveHead {false};

    // 选择区域相关
    int mSelectionStart {};
    int mCurrentPosition {};
    QTextCursor mSelectedCursor {};
    // 行首相关词
    QString mPrompt {};
    QString mRelativePath {};
    // 命令历史
    int mIndexOfHistory {-1};
    int mCountOfHistory {0};
    QStringList mHistoryCommands{};
    QString mCurrentCommand {};

    // 相关bool
    bool mIsShowPrompt {false};
    bool mIsExecStarted {false};

    // actions
    QAction* mZoomIn {nullptr};
    QAction* mZoomOut {nullptr};

    // color
    QColor mErrorColor {Qt::red};
    QColor mWarningColor {Qt::yellow};
    QColor mInfoColor {Qt::white};
    QColor mBackGroundColor {Qt::black};
    QColor mPromptColor {Qt::green};
    QColor mSelectionColor = palette().color(QPalette::Highlight);
};

#endif // SSHCONSOLE_H
